package dao;

import web.Option;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class OptionDao {
    public int optID;
    public String answer;
    public int qid;
    public OptionDao(){}

    public OptionDao(String answer,int qid){
        this.answer=answer;
        this.qid=qid;
    }

    private static Connection connection=DBConnection.getDBCourseConnection();

    public OptionDao(int optID, String answer) {
        this.optID=optID;
        this.answer=answer;
    }

    public static int add(OptionDao option){
        int result=0;
        try {
            CallableStatement addQuestion=connection.prepareCall("{call add_option(?,?,?)}");
            addQuestion.setString(1,option.answer);
            addQuestion.setInt(2,option.qid);
            addQuestion.registerOutParameter(3, Types.INTEGER);
            addQuestion.execute();
            result=addQuestion.getInt(3);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static List<OptionDao> getOptionsByQid(int qid) {
        ResultSet result;
        List<OptionDao> options=new ArrayList<>();
        try {
            CallableStatement getOption=connection.prepareCall("{call select_option(?)}");
            getOption.setInt(1,qid);
            result=getOption.executeQuery();
            while (result.next()){
                int optID=result.getInt(1);
                String answer=result.getString(2);
                OptionDao option=new OptionDao(optID,answer);
                options.add(option);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return options;
    }
}
